package com.ssy.lingxi.marketing.handler.convert;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.response.ResponseCode;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * Jpa 将 Postgresql Json(或Jsonb)字段转换为Map<String, BigDecimal>
 * @author yzc
 * @version 2.0.0
 * @date 2021/7/16
 */
@Converter(autoApply = true)
public class JpaJsonToMapConverter implements AttributeConverter<Map<String, BigDecimal>, String> {
    private final static ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public String convertToDatabaseColumn(Map<String, BigDecimal> attribute) {
        try {
            if (attribute == null) {
                attribute = Collections.emptyMap();
            }
            return objectMapper.writeValueAsString(attribute);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ResponseCode.BUSINESS_ERROR, "数据库Json字段写入错误");
        }
    }

    @Override
    public Map<String, BigDecimal> convertToEntityAttribute(String dbData) {
        try {
            if (dbData == null) {
                return new HashMap<>();
            }

            return objectMapper.readValue(dbData, new TypeReference<Map<String, BigDecimal>>() {
            });
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ResponseCode.BUSINESS_ERROR, "数据库Json字段写入错误");
        }
    }
}
